<?php

!defined('IN_HDWIKI') && exit('Access Denied');

class bannedmodel {

	var $db;
	var $base;

	function bannedmodel(&$base) {
		$this->base = $base;
		$this->db = $base->db;
	}

	function get_ip_list(){
		$bannedlist = array();
		$this->refresh_ip();
		$query = $this->db->query("SELECT * FROM `".DB_TABLEPRE."banned` ORDER BY id DESC");
		while($banned = $this->db->fetch_array($query)){
			$banned['endtime'] = $this->base->date($banned['time']+$banned['expiration']);
			$banned['starttime'] = $this->base->date($banned['time']);
			if($banned['ip1']<0)$banned['ip1'] = '*';
			if($banned['ip2']<0)$banned['ip2'] = '*';
			if($banned['ip3']<0)$banned['ip3'] = '*';
			if($banned['ip4']<0)$banned['ip4'] = '*';
			$banned['ip'] = $banned['ip1'].'.'.$banned['ip2'].'.'.$banned['ip3'].'.'.$banned['ip4'];
			$bannedlist[] = $banned;
		}
		return $bannedlist;
	}

	function add_ip($ip1,$ip2,$ip3,$ip4,$expiration,$username){
		$expiration=($expiration)? $expiration*3600*24 : 0;
		$ip1=($ip1!='*') ? intval($ip1) : -1;
		$ip2=($ip2!='*') ? intval($ip2) : -1;
		$ip3=($ip3!='*') ? intval($ip3) : -1;
		$ip4=($ip4!='*') ? intval($ip4) : -1;
		if($ip1>255 || $ip2>255 || $ip3>255 || $ip4>255){
			return false;
		}
		$id = $this->db->result_first("SELECT id FROM `".DB_TABLEPRE."banned` WHERE ip1 = '{$ip1}' AND ip2 = '{$ip2}' AND ip3 = '{$ip3}' AND ip4 = '{$ip4}' LIMIT 1");
		if(!$id){
			$this->db->query("INSERT INTO `".DB_TABLEPRE."banned` (`ip1`,`ip2`,`ip3`,`ip4`,`admin`,`time`,`expiration`) VALUES ('{$ip1}','{$ip2}','{$ip3}','{$ip4}','{$username}','{$this->base->time}','{$expiration}')");
			$this->updatebannedip();
			return true;
		}
		return false;
	}

	function del_ip($ips){
		$this->db->query("DELETE FROM `".DB_TABLEPRE."banned` WHERE id IN (' ".implode("','",$ips)."')");
		$this->updatebannedip();
	}

	function refresh_ip(){
		$this->db->query("DELETE FROM `".DB_TABLEPRE."banned` WHERE (`time`+`expiration`)<{$this->base->time}");
	}
	
	function updatebannedip(){
		$ips=$this->get_ip_list();
		$this->base->cache->writecache('bannedip', $ips);
	}
}
?>